package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: hjk
 * @Date: 2019/6/22 23:42
 * @Description:
 */
@Component
public class JwtInterceptor implements HandlerInterceptor{

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 无论如何都放行，具体能不能操作还是具体的操作中判断
        // 拦截器只负责把请求头中包含的token令牌进行解析
        String header = request.getHeader("Authorization");
        if(!StringUtils.isEmpty(header)){
            if(header.startsWith("Bearer ")){
                String token = header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    if(!StringUtils.isEmpty(roles) && StringUtils.equals("admin",roles)){
                        request.setAttribute("claims_admin",token);
                    }
                    if(!StringUtils.isEmpty(roles) && StringUtils.equals("user",roles)){
                        request.setAttribute("claims_user",token);
                    }
                }catch (Exception e){
                    throw new RuntimeException("token parse error");
                }
            }
        }
        return true;
    }
}
